package ccnt.pvc.scudewaremobile.invokedemo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import ccnt.pvc.scudwaremobile.bean.ScudRequest;
import ccnt.pvc.scudwaremobile.dao.ServiceModel;
import ccnt.pvc.scudwaremobile.utils.Constants.MessageCode;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class MainActivity extends Activity implements OnClickListener {

	private static final String TAG = MainActivity.class.getName();
	private static final String PACKAGENAME = "ccnt.pvc.scudewaremobile.invokedemo";
	
	Button btnQuery;
	Button btnRegister;
	Button btnUnregister;
	Button btnRequest;
	TextView txtResult;
	Spinner sleProbe;
	String className = "unknown";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		btnQuery = (Button)findViewById(R.id.btnQuery);
		btnQuery.setOnClickListener(this);
		
		btnRequest = (Button)findViewById(R.id.btnRequest);
		btnRequest.setOnClickListener(this);
		
		btnRegister = (Button)findViewById(R.id.btnRegister);
		btnRegister.setOnClickListener(this);
		
		btnUnregister = (Button)findViewById(R.id.btnUnregister);
		btnUnregister.setOnClickListener(this);
		
		txtResult = (TextView)findViewById(R.id.txtResult);
		txtResult.setMovementMethod(ScrollingMovementMethod.getInstance());
		sleProbe = (Spinner)findViewById(R.id.sleProbe);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	boolean isBind = false;
	Messenger messenger = null;
	
	private final ServiceConnection serviceConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName className) {
			isBind = false;
			messenger = null;
		}
		
		@Override
		public void onServiceConnected(ComponentName className, IBinder binder) {
			isBind = true;
			messenger = new Messenger(binder);
		}
	};
	
	@Override
	protected void onStart() {
		super.onStart();
		Intent intent = new Intent();
		intent.setClassName("ccnt.pvc.scudwaremobile", "ccnt.pvc.scudwaremobile.service.MainService");
		bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onStop() {
		if(isBind)
			unbindService(serviceConnection);
		super.onStop();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		Message msg = Message.obtain(null, MessageCode.SCUDEWARE_MESSAGE, 0, 0);
		msg.replyTo = mMessager;
		
		ScudRequest request = new ScudRequest();
		request.setRegisterName(PACKAGENAME);
		
		ServiceModel service = new ServiceModel();
		service.setClassName(className);
		request.addService(service);
		
		if(R.id.btnRequest == id) {
			request.setAction(ScudRequest.ACTION_REQUEST);
		}
		else if(R.id.btnRegister == id) {
			request.setAction(ScudRequest.ACTION_REGISTER);
		}
		else if(R.id.btnUnregister == id) {
			request.setAction(ScudRequest.ACTION_UNREGISTER);
		}
		else if(R.id.btnQuery == id) {
			request.setAction(ScudRequest.ACTION_QUERY);
		}
		
		Bundle bundle = new Bundle();
		bundle.putString("ScudRequest", new Gson().toJson(request));
		msg.setData(bundle);
		
		try {
			messenger.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
	
	class IncomingHandler extends Handler {
		
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
				case MessageCode.RESPONSE_REQUEST:
					Log.d(TAG, "receive response");
					Log.d(TAG, msg.getData().getString("data"));
					txtResult.setText(msg.getData().getString("data"));
					break;
				case MessageCode.RESPONSE_QUERY: 
					Log.d(TAG, "receive query response");
					String jsonProbes = msg.getData().getString("services");
					List<ServiceModel> services = new ArrayList<ServiceModel>();
					services = new Gson().fromJson(jsonProbes,
						new TypeToken<List<ServiceModel>>() {
						}.getType());
					final List<String> classNames = new ArrayList<String>();
					for(ServiceModel service : services) {
						classNames.add(service.getClassName());
					}
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, classNames);
					sleProbe.setAdapter(adapter);
					sleProbe.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							className = classNames.get(arg2);
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
							// TODO Auto-generated method stub
							
						}
					});
					break;
				default:
					super.handleMessage(msg);
			}
		}
	}
	final Messenger mMessager = new Messenger(new IncomingHandler());

}
